import envConfig from "@/config/env.ts";

interface RequestOption {
  url: string;
  method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
  data?: any;
  header?: Record<string, string>;
  timeout?: number;
}

const request = (options: RequestOption): Promise<any> => {
  // 请求拦截
  const token = uni.getStorageSync("token");
  // const token = "af310e89-ab5c-4297-b6de-6a13941a1dff";

  return new Promise((resolve, reject) => {
    uni.request({
      url: envConfig.baseURL + options.url,
      method: options.method || "GET",
      data: options.data || {},
      timeout: options.timeout || 60000,
      header: {
        Accept: "application/json, text/plain, */*",
        Authorization: token ? `Bearer ${token}` : "",
        "Content-Type": "application/json",
        ...options.header,
      },
      success: (res) => {
        // 响应拦截
        if (res.statusCode === 200) {
          resolve(res.data);
        } else if (res.statusCode === 401) {
          // token过期或未授权处理
          uni.removeStorageSync("token");
          uni.showToast({
            title: "登录已过期，请重新登录",
            icon: "none",
          });
          // 可以跳转到登录页
          // uni.redirectTo({ url: '/pages/login/login' });
          reject(res);
        } else {
          uni.showToast({
            title: res.data?.message || "请求失败",
            icon: "none",
          });
          reject(res);
        }
      },
      fail: (err) => {
        uni.showToast({
          title: "网络请求失败",
          icon: "none",
        });
        reject(err);
      },
    });
  });
};

export default request;
